package com.test.client;

import com.alibaba.fastjson.JSON;
import com.test.coder.Decoder;
import com.test.coder.Encoder;
import com.test.client.handler.TcpClientHandler;
import com.test.message.LoginRequestMessage;
import com.test.message.Message;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TcpClient {

    public static String HOST = "localhost";
    public static int PORT = 9991;

    public static Bootstrap bootstrap = getBootstrap();
    public static Channel channel = getChannel(HOST, PORT);


    public static Bootstrap getBootstrap() {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class);
        b.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
                pipeline.addLast(new Encoder());
                pipeline.addLast(new Decoder());
                pipeline.addLast("handler", new TcpClientHandler());
            }
        });
        b.option(ChannelOption.SO_KEEPALIVE, true);
        return b;
    }

    public static Channel getChannel(String host, int port) {
        Channel channel;
        try {
            channel = bootstrap.connect(host, port).sync().channel();
        } catch (Exception e) {
            log.error("连接Server{},{}失败%n", host, port);
            return null;
        }
        return channel;
    }

    public static void sendMsg(Object msg) throws Exception {
        if (channel != null) {
            channel.writeAndFlush(msg).sync();
            log.info("消息已发送！");
        } else {
            log.error("消息发失败?,连接尚未建立!");
        }
    }

    public static void main(String[] args) {
        try {

            LoginRequestMessage loginRequestMessage = new LoginRequestMessage();
            loginRequestMessage.setCcid("45222255662");
            loginRequestMessage.setImei("222222222");
            loginRequestMessage.setSignal(31);
            loginRequestMessage.setVersion(1);

            byte[] bytes = JSON.toJSONBytes(loginRequestMessage);


            Message message = new Message();
            message.setHead((short) 0xBB);
            message.setFunCode((byte) 0x10);
            message.setMessageLength((short) bytes.length);

//            byte[] messageData;
//            messageData = s.getBytes();
            message.setMessageData(bytes);
            message.setCrc((short) 1);
            TcpClient.sendMsg(message);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
